<?php
define("AUTH_SECRET_KEY", 'tamtay shared secret');
define("AUTH_APP_ID", 'TAMTAY' );
define("SGAME_PATH_LOGIN", 'http://pay.sgame.vn/login/tamtay_changepass.php');

class TT_Base_Action extends Zend_Controller_Action
{
	protected static $data_cache=null;
	protected static $data_cachedb=null;
	
	public function preDispatch()
	{
		$view = $this->_helper->viewRenderer->view;
		
		if ($view!=null)
		{
			$view->controller=$this;
		}
	}
	
	public function getUser()
	{
		return Zend_Registry::get("user");
	}

	public function	loadModel($model)
	{
		return AppGlobal::loadModel($model);
	}
	
	//lazy load user roles
	public function loadUserRoles()
	{
		$u = Zend_Registry::get("user");
		if ($u->uid == 0) {
			return;
		}
		if ($u->roles_loaded) {
			return;
		}    		
		$roleModel = $this->loadModel("Role");
		$roles = $roleModel->getUserRoles($u->uid);              
        if ($roles) {
            foreach ($roles as $role) {
                $u->roles[] = $role->rid;
            }
        }    		
		$u->roles_loaded = TRUE;          
		Zend_Registry::set("user", $u);
	}
	
	//Lazy load user permissions
	public function loadUserPermissions()
	{
		$u = Zend_Registry::get("user");
		if ($u->uid == 0) {
			return;
		}
		if ($u->perms_loaded) {
			return;
		}                     		
		if ( ! $u->roles_loaded) {
			$this->loadUserRoles();
		}     		
		$permissionModel = $this->loadModel('Permission');     
        $perms = $permissionModel->getUserPermissions($u->uid, array_values($u->roles));            
        if ($perms) {
            foreach ($perms as $p) {
                $u->perms[] = $p->permission;
            }
        }
		$u->perms_loaded = TRUE;
		Zend_Registry::set("user", $u);
	}
	
	//check current user permission
	public function hasPerm($perm)
	{
		$u = Zend_Registry::get("user");           
		if ( ! $u->perms_loaded)
		{
			$this->loadUserPermissions();
		}               
		if (in_array($perm, $u->perms)) {
            return TRUE;
        }
        return FALSE;           
	}
	
	public function getVar($varname, $defval=null)
	{
		$vars=Zend_Registry::get("variables");
		if ($vars==null)
		{
			$cache_key="system_variables";
			$vars=$this->getCache($cache_key);
			if ($vars===false)
			{
				$v_model=$this->loadModel("Vars");
				$vars=$v_model->loadVars();
				$this->setCache($cache_key, $vars, 60*60*24);
			}
			if (is_array($vars))
			{
				Zend_Registry::set("variables", $vars);
			}
		}
		if (is_array($vars))
		{
			if (array_key_exists($varname, $vars))
			{
				return $vars[$varname];
			}
		}
		return $defval;
	}
	
	public function setVar($vaname, $value)
	{
		$v_model=$this->loadModel("Vars");
		$v_model->setVar($vaname, $value);
		$cache_key="system_variables";
		$this->deleteCache($cache_key);
		Zend_Registry::set("variables", null);
	}
    
}